package com.naiterui.ehp.bs.im.network.mqtt.pool;

import org.apache.commons.pool2.impl.GenericObjectPool;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MqttConnection {

    private static Logger LOGGER = LoggerFactory.getLogger(MqttConnection.class);

    /**
     * MQTT Broker客户端连接对象
     */
    private MqttClient mqttClient;

    /**
     * 隶属于的连接池
     */
    private GenericObjectPool<MqttConnection> belongedPool;

    public MqttConnection(MqttClient mqttClient) {
        this.mqttClient = mqttClient;
    }

    /**
     * 推送方法消息
     */
    public void publish(String topic, String message, String ecodeCharset, Integer... qos) throws Exception {
        MqttMessage mqttMessage = new MqttMessage();
        mqttMessage.setPayload(message.getBytes(ecodeCharset));
        if (qos.length > 0) {
            mqttMessage.setQos(qos[0]);
        }
        this.mqttClient.publish(topic, mqttMessage);
    }

    /**
     * 设置回调操作类
     */
    public void setCallBack(MqttCallback callback) {
        this.mqttClient.setCallback(callback);
    }

    /**
     * 订阅主题
     */
    public void subscribe(String topicFilter, int qos) throws MqttException {
        this.mqttClient.subscribe(topicFilter, qos);
    }

    /**
     * 换回连接池
     */
    public void close() {
        this.belongedPool.returnObject(this);
    }

    /**
     * 销毁连接
     */
    public void destroy() {
        try {
            if (this.mqttClient.isConnected()) {
                this.mqttClient.disconnect();
            }
            this.mqttClient.close();
        } catch (Exception e) {
            LOGGER.error("MqttConnection destroy ERROR ; errorMsg={}", e.getMessage(), e, e);
        }
    }

    public GenericObjectPool<MqttConnection> getBelongedPool() {
        return belongedPool;
    }

    public void setBelongedPool(GenericObjectPool<MqttConnection> belongedPool) {
        this.belongedPool = belongedPool;
    }

    public MqttClient getMqttClient() {
        return mqttClient;
    }

    public void setMqttClient(MqttClient mqttClient) {
        this.mqttClient = mqttClient;
    }

}
